// 自定义数据集入参
import React from 'react';
import { Row, Col, Button, Icon, Divider, Popconfirm, message, Input, Modal, Form } from 'antd';
import { $http } from 'containers/config/https';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx'; // 公共table组件
import 'assets/css/common.css';
import '../style/index.less';

class CustomDataEntryParameters extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            columns: [],
            tableData: [],
            total: 0,
            page: 1,
            pageSize: 10,
            userInfo: {},
            flag: 'add',
            mainRowData: {}
        }
    }

    componentDidMount() {
        this.props.onRef(this)
    }
    
	// 调用公共组件的连接事件
	onRef = (ref) => {
		this.child = ref
    }
    
    // 关闭弹窗
    handleCancel = () => {
        this.setState({visible: false}, () => {
            this.setState({userInfo: {}, flag: 'add'});
            this.resetFields();
        })
    }

    // 打开弹窗
    showModal = (record) => {
        this.setState({
            visible: true,
            mainRowData: record
        }, () => {
            if(!(this.state.columns&&this.state.columns.length > 0)) {
                this.getColumnsData(); // 初始化表头数据
            }
            this.handleQuery(); // 初始化列表数据
        })
    }

    // 获取表头数据
    getColumnsData = () => {
        let columns = [
            {
                title: '数据集入参代码',
                dataIndex: 'code',
                align: "center",
                width: '200px'
            },
            {
                title: '数据集入参描述',
                dataIndex: 'descripts',
                align: "center",
                width: '200px'
            },
			{
                title: '操作',
                dataIndex: 'operation',
                align: "center",
                width: '130px',
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{color: '#108EE9'}}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        {/* 分割线 */}
                        <Divider type="vertical" />
                        <Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                            <span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
                        </Popconfirm>
                    </span>
                ),
			}
        ]
        this.setState({columns});
    }
    
    // 查询
    handleQuery = () => {
        // this.setState({page: 1, pageSize: 10}, () => {
            this.getTableData();
        // })
    }

    // 获取表格数据
    getTableData = () => {
        // this.setState({loading: true})
        let {page, pageSize, mainRowData} = this.state;
        let obj = this.props.form.getFieldsValue();
		let data = {
			params: [{
				code: obj.code, // 数据集代码
                descripts: obj.descripts, // 数据集描述
                CBEMRDSParRef: mainRowData.ID,
			}],
			pagination: [{
				pageSize: 10000,
				currentPage: 1
			}]
		}
		$http.post('urlS', this, {
			code: "06010021",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.length; i++) {
                        res.result[i].key = i;
					}
					this.setState({ tableData: res.result, total: res.result&&res.result.length > 0 ? res.result.length : 0 })
					// 数据加载成功关闭loading
					this.child.handleLoading();
				} else {
					this.setState({ tableData: [], total: 0 })
					// 数据加载失败关闭loading
					this.child.handleLoading();
				}
			},
			error: function (error) {
				this.setState({ tableData: [], total: 0 }, () => {
					// 数据加载成功关闭loading
					this.child.handleLoading();
				})
			}
		})
    }

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.getTableData();
		})
    }
    
    handleSave = () => {
        if (this.state.flag === 'add') {
            this.handelSave('06010022', '新增')
        } else if (this.state.flag === 'compile') {
            this.handelSave('06010023', '编辑')
        }
    }

    // 编辑
    handleCompile = record => {
        this.resetFields();
        this.setState({flag: 'compile', userInfo: record})
    }

    handelSave = (code, msg) => {
        const { form: { validateFields } } = this.props;
        validateFields((errors, values) => {
            // 验证成功
            if (errors === null) {
                let data = {
                    params: []
                }
                let obj = JSON.parse(JSON.stringify(values));
                // 当增加时点击复制把ID值传给后天然后后台根据ID值去复制权限，编辑时则根据ID去保存修改
                if (msg === '编辑') {
                    obj.ID = this.state.userInfo.ID
                } else {
                    obj.CBEMRDSParRef = this.state.mainRowData.ID;
                }

                // 处理需要传递的obj
                data.params.push(obj);
                $http.post('urlADS', this, {
                    code: code,
                    data: data,
                    success: function (res) { 
                        if (+res.errorCode === 0) {
                            // 成功提示
                            message.success(msg + '成功');
                            // 新增或编辑成功重置form表单
                            this.resetFields();
                            this.props.form.setFieldsValue({code: undefined, descripts: undefined});
                            this.setState({userinfo: {}, flag: 'add'}, () => {
                                // 刷新列表数据
                                this.handleQuery();
                            })
                        }
                    }
                })
            }
        });
    }

    // 删除
    handleDelete = record => {
        let data = {
			params: [{
				ID: record.ID
			}]
		}
		$http.post('urlADS', this, {
			code: '06010024',
			data: data,
			success: function (res) { 
				if (+res.errorCode === 0) {
					message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
                    this.resetFields();
                    this.setState({userInfo: {}, flag: 'add'}, () => {
                        this.getTableData();
                    })
				}
			}
		})
    }

    // 重置表单
    resetFields() {
        this.props.form.resetFields();
    }
    
    render() {
        let {visible, columns, tableData, total, page, userInfo, flag} = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemInput  = {
            labelCol: {span: 10},
            wrapperCol: {span: 14}
        };
        // 组件所需参数
		const param = {
			// 表头配置
			columns,
			// 表格数据
			data: tableData,
			// 数据总条数
			// total,
			// 当前页数
            // page, 
            x: 530,
            // 表格的宽度
			y: 300,
            height: '345px',
		}
        return (
            <Modal
                visible={visible}
                title="自定义数据集入参"
                footer={null}
                onCancel={this.handleCancel}
                width={800}
                className="custom-data"
            >
                <div>
                    <Form>
                        <Row>
                            <Col span={16}>
                                <Row>
                                    <Col span={12}>
                                        <Form.Item label="数据集代码：" {...formItemInput}>
                                            {getFieldDecorator('code', {
                                                initialValue: userInfo.code ? userInfo.code: undefined,
                                                rules: [{ required: true, message: '数据集代码不能为空' }]
                                            })(
                                                <Input
                                                    placeholder="请输入"
                                                    onPressEnter={this.handleQuery}
                                                />
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label="数据集名称：" {...formItemInput}>
                                            {getFieldDecorator('descripts', {
                                                initialValue: userInfo.descripts ? userInfo.descripts: undefined,
                                                rules: [{ required: true, message: '数据集名称不能为空' }]
                                            })(
                                                <Input
                                                    placeholder="请输入"
                                                    onPressEnter={this.handleQuery}
                                                />
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Col>
                            <Col span={8} style={{textAlign: 'center'}}>
                                <Button onClick={this.handleQuery} style={{ margin: '4px 15px 0 0'}}>查询</Button>
                                <Button onClick={this.handleSave} style={{ background: 'rgba(247,128,93,1)', color: '#fff', marginTop: '4px'}}>{flag === 'add' ? '新增' : '编辑'}</Button>
                            </Col>
                        </Row>
                    </Form>
                </div>
                <div style={{padding: '12px'}} className="table-body-height">
                    {/* handelThis将夫组件的属性与方法给子组件访问 */}
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
            </Modal>
        )
    }
};
const CustomDataEntryParametersForm = Form.create()(CustomDataEntryParameters);
export default CustomDataEntryParametersForm;